<template>
  <view class="record-popup" v-if="show" @touchmove.stop.prevent>
    <view class="popup-mask" @tap="closeModal"></view>
    <view class="popup-content-wrapper">
      <view class="popup-header">
        <text class="title">添加记录</text>
        <text class="close" @tap="closeModal">×</text>
      </view>
      <view class="popup-content">
        <view class="form-item">
          <text class="label">联系人</text>
          <view class="contact-info">
            <text class="contact-name">{{ contactName }}</text>
          </view>
        </view>

        <view class="form-item">
          <text class="label">礼簿</text>
          <view class="giftbook-select">
            <picker 
              :value="selectedGiftBookIndex" 
              :range="giftBooks" 
              range-key="title"
              @change="handleGiftBookChange"
              :disabled="!giftBooks || giftBooks.length === 0"
            >
              <view class="picker">
                <text v-if="selectedGiftBook && selectedGiftBook.title">{{ selectedGiftBook.title }}</text>
                <text v-else>{{ giftBooks && giftBooks.length > 0 ? '请选择礼簿' : '暂无可用礼簿' }}</text>
                <text class="arrow">▼</text>
              </view>
            </picker>
          </view>
          <view class="error-tip" v-if="errors.giftBook">{{ errors.giftBook }}</view>
        </view>

        <view class="form-item">
          <text class="label">类型</text>
          <view class="radio-group">
            <view 
              class="radio-item" 
              :class="{'radio-item-active': formData.type === 'receive'}"
              @tap="formData.type = 'receive'"
            >
              <text class="radio-icon">{{ formData.type === 'receive' ? '●' : '○' }}</text>
              <text class="radio-label">收礼</text>
            </view>
            <view 
              class="radio-item" 
              :class="{'radio-item-active': formData.type === 'give'}"
              @tap="formData.type = 'give'"
            >
              <text class="radio-icon">{{ formData.type === 'give' ? '●' : '○' }}</text>
              <text class="radio-label">送礼</text>
            </view>
          </view>
        </view>

        <view class="form-item">
          <text class="label">金额</text>
          <input 
            class="input" 
            type="digit"
            v-model="formData.amount"
            placeholder="请输入金额"
            @input="handleAmountInput"
            :class="{'input-error': errors.amount}"
          />
          <view class="error-tip" v-if="errors.amount">{{ errors.amount }}</view>
        </view>
        
        <view class="form-item">
          <text class="label">礼品</text>
          <input 
            class="input" 
            v-model="formData.giftName"
            placeholder="请输入礼品名称（选填）"
            @input="handleGiftNameInput"
            :class="{'input-error': errors.giftName}"
          />
          <view class="error-tip" v-if="errors.giftName">{{ errors.giftName }}</view>
        </view>

        <view class="form-item">
          <text class="label">备注</text>
          <textarea 
            class="textarea" 
            v-model="formData.remark"
            placeholder="请输入备注（选填）"
            @input="handleRemarkInput"
            :class="{'textarea-error': errors.remark}"
          />
          <view class="error-tip" v-if="errors.remark">{{ errors.remark }}</view>
        </view>
      </view>
      <view class="popup-footer">
        <button 
          class="submit-btn" 
          @tap="handleSubmit"
          :disabled="!isValid"
        >
          确定
        </button>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue';
import { useGiftBookStore } from '@/store/modules/giftbook';
import type { GiftBook } from '@/types/giftbook';

const props = defineProps({
  show: {
    type: Boolean,
    default: false
  },
  contactId: {
    type: String,
    required: true
  },
  contactName: {
    type: String,
    required: true
  }
});

const emit = defineEmits(['close', 'submit']);

const giftBookStore = useGiftBookStore();

// 表单数据
const formData = ref({
  type: 'receive',
  amount: '',
  giftName: '',
  remark: '',
  giftBookId: ''
});

// 错误状态管理
const errors = ref({
  giftBook: '',
  amount: '',
  giftName: '',
  remark: ''
});

// 选中的礼簿索引
const selectedGiftBookIndex = ref(0);

// 获取所有礼簿
const giftBooks = computed(() => {
  // 确保返回的是一个数组
  const books = giftBookStore.getAllGiftBooks || [];
  // 调试输出
  console.log('【添加记录弹窗】礼簿列表:', JSON.stringify(books));
  return books;
});

// 选中的礼簿
const selectedGiftBook = computed(() => {
  if (!giftBooks.value || giftBooks.value.length === 0) {
    return null;
  }
  return giftBooks.value[selectedGiftBookIndex.value];
});

// 表单验证
const isValid = computed(() => {
  // 检查礼簿是否可用
  const hasValidGiftBook = giftBooks.value && giftBooks.value.length > 0 && selectedGiftBook.value;
  
  return hasValidGiftBook && 
         formData.value.type && 
         formData.value.amount && 
         /^\d+(\.\d{0,2})?$/.test(formData.value.amount);
});

// 重置表单
const resetForm = () => {
  formData.value = {
    type: 'receive',
    amount: '',
    giftName: '',
    remark: '',
    giftBookId: ''
  };
  selectedGiftBookIndex.value = 0;
  errors.value = {
    giftBook: '',
    amount: '',
    giftName: '',
    remark: ''
  };
};

// 关闭弹窗
const closeModal = () => {
  resetForm();
  emit('close');
};

// 处理礼簿选择
const handleGiftBookChange = (e: any) => {
  const index = e.detail.value;
  console.log(`【添加记录弹窗】选择礼簿索引: ${index}, 礼簿数量: ${giftBooks.value.length}`);
  
  if (index >= 0 && index < giftBooks.value.length) {
    selectedGiftBookIndex.value = index;
    const selectedBook = giftBooks.value[index];
    if (selectedBook && selectedBook.id) {
      formData.value.giftBookId = selectedBook.id;
      console.log(`【添加记录弹窗】选中礼簿: ${selectedBook.title}, ID: ${selectedBook.id}`);
    } else {
      console.warn('【添加记录弹窗】选中礼簿对象异常:', selectedBook);
    }
  } else {
    console.warn(`【添加记录弹窗】选择的索引超出范围: ${index}`);
  }
};

// 金额输入验证
const validateAmount = () => {
  if (!formData.value.amount) {
    errors.value.amount = '请输入金额';
    return false;
  }
  if (!/^\d+(\.\d{0,2})?$/.test(formData.value.amount)) {
    errors.value.amount = '金额格式不正确';
    return false;
  }
  errors.value.amount = '';
  return true;
};

// 礼品名称输入验证
const validateGiftName = () => {
  if (formData.value.giftName && formData.value.giftName.length > 50) {
    errors.value.giftName = '礼品名称不能超过50个字符';
    return false;
  }
  errors.value.giftName = '';
  return true;
};

// 备注输入验证
const validateRemark = () => {
  if (formData.value.remark && formData.value.remark.length > 200) {
    errors.value.remark = '备注不能超过200个字符';
    return false;
  }
  errors.value.remark = '';
  return true;
};

// 处理金额输入
const handleAmountInput = () => {
  validateAmount();
};

// 处理礼品名称输入
const handleGiftNameInput = () => {
  validateGiftName();
  if (formData.value.giftName.length > 50) {
    formData.value.giftName = formData.value.giftName.slice(0, 50);
  }
};

// 处理备注输入
const handleRemarkInput = () => {
  validateRemark();
  if (formData.value.remark.length > 200) {
    formData.value.remark = formData.value.remark.slice(0, 200);
  }
};

// 初始化函数
const initData = async () => {
  try {
    console.log('【添加记录弹窗】正在加载礼簿数据...');
    
    // 加载礼簿数据
    await giftBookStore.loadFromStorage();
    
    // 打印礼簿数据检查格式
    console.log('【添加记录弹窗】礼簿数据列表:', JSON.stringify(giftBooks.value));
    
    // 如果有礼簿数据，默认选中第一个
    if (giftBooks.value && giftBooks.value.length > 0) {
      selectedGiftBookIndex.value = 0;
      const firstBook = giftBooks.value[0];
      if (firstBook && firstBook.id) {
        formData.value.giftBookId = firstBook.id;
        console.log(`【添加记录弹窗】已选中默认礼簿: ${firstBook.title}, ID: ${firstBook.id}`);
      } else {
        console.warn('【添加记录弹窗】第一个礼簿对象异常:', firstBook);
      }
    } else {
      console.log('【添加记录弹窗】没有可用的礼簿数据');
    }
  } catch (error) {
    console.error('【添加记录弹窗】加载礼簿数据失败:', error);
  }
};

// 使用onMounted确保组件挂载时初始化数据
onMounted(() => {
  initData();
});

// 提交表单
const handleSubmit = () => {
  // 检查礼簿是否存在
  if (!giftBooks.value || giftBooks.value.length === 0) {
    errors.value.giftBook = '没有可用的礼簿，请先创建礼簿';
    uni.showToast({
      title: '请先创建礼簿',
      icon: 'none'
    });
    return;
  }
  
  if (!selectedGiftBook.value) {
    errors.value.giftBook = '请选择礼簿';
    return;
  }
  
  if (!validateAmount()) {
    return;
  }
  
  const now = new Date().getTime();
  
  emit('submit', {
    contactId: props.contactId,
    contactName: props.contactName,
    giftBookId: selectedGiftBook.value.id,
    type: formData.value.type,
    amount: Number(formData.value.amount),
    giftName: formData.value.giftName || '',
    remarks: formData.value.remark || '',
    createTime: now,
    updateTime: now
  });
  
  resetForm();
};

// 监听show属性变化
watch(() => props.show, (newVal) => {
  if (newVal) {
    resetForm();
    // 重新初始化数据
    initData();
  }
});
</script>

<style lang="scss">
.record-popup {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 999;
  display: flex;
  justify-content: center;
  align-items: center;

  .popup-mask {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
  }

  .popup-content-wrapper {
    position: relative;
    width: 90%;
    max-height: 90%;
    background-color: #fff;
    border-radius: 16rpx;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    animation: slideIn 0.3s ease;

    @keyframes slideIn {
      from {
        transform: translateY(50rpx);
        opacity: 0;
      }
      to {
        transform: translateY(0);
        opacity: 1;
      }
    }
  }

  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 24rpx;
    border-bottom: 1rpx solid #f0f0f0;

    .title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }

    .close {
      font-size: 48rpx;
      color: #999;
      line-height: 1;
    }
  }

  .popup-content {
    padding: 24rpx;
    overflow-y: auto;
    max-height: 70vh;

    .form-item {
      margin-bottom: 24rpx;

      .label {
        display: block;
        font-size: 28rpx;
        color: #333;
        margin-bottom: 12rpx;
      }

      .contact-info {
        padding: 16rpx 24rpx;
        background-color: #f8f8f8;
        border-radius: 8rpx;
        
        .contact-name {
          font-size: 28rpx;
          color: #333;
        }
      }

      .giftbook-select {
        .picker {
          width: 100%;
          height: 80rpx;
          line-height: 80rpx;
          padding: 0 24rpx;
          font-size: 28rpx;
          color: #333;
          background-color: #f8f8f8;
          border-radius: 8rpx;
          box-sizing: border-box;
          display: flex;
          justify-content: space-between;
          align-items: center;
          
          .arrow {
            color: #999;
            font-size: 24rpx;
          }
        }
      }

      .input, .textarea {
        width: 100%;
        height: 80rpx;
        line-height: 80rpx;
        padding: 0 24rpx;
        font-size: 28rpx;
        color: #333;
        background-color: #f8f8f8;
        border-radius: 8rpx;
        box-sizing: border-box;
      }

      .textarea {
        height: 160rpx;
        line-height: 1.5;
        padding: 16rpx 24rpx;
      }
    }
  }

  .popup-footer {
    margin-top: 32rpx;
    padding: 16rpx 24rpx 32rpx;
    border-top: 1px solid #f5f5f5;

    .submit-btn {
      width: 100%;
      height: 88rpx;
      line-height: 88rpx;
      text-align: center;
      font-size: 32rpx;
      color: #fff;
      background-color: #1890ff;
      border-radius: 44rpx;

      &:disabled {
        opacity: 0.6;
      }
    }
  }
}

.radio-group {
  display: flex;
  gap: 20rpx;
  
  .radio-item {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 16rpx 24rpx;
    background-color: #f8f8f8;
    border-radius: 8rpx;
    transition: all 0.2s ease;
    border: 1rpx solid #eee;
    
    &:active {
      transform: scale(0.98);
    }
    
    &-active {
      &.radio-item[class*="radio-item"] {
        border-color: var(--primary-color);
      }
      
      &:nth-child(1) {
        background-color: rgba(24, 144, 255, 0.1);
        
        .radio-icon, .radio-label {
          color: #1890ff;
        }
      }
      
      &:nth-child(2) {
        background-color: rgba(255, 82, 82, 0.1);
        
        .radio-icon, .radio-label {
          color: #ff5252;
        }
      }
    }
    
    .radio-icon {
      font-size: 32rpx;
      color: #999;
      margin-right: 8rpx;
    }
    
    .radio-label {
      font-size: 28rpx;
      color: #333;
      font-weight: 500;
    }
  }
}

.input-error, .textarea-error {
  border: 1px solid #ff4d4f !important;
  background-color: #fff2f0 !important;
}

.error-tip {
  font-size: 24rpx;
  color: #ff4d4f;
  margin-top: 8rpx;
  line-height: 1.2;
}
</style> 